package com.gjq.springboot.controller;

import com.gjq.springboot.entity.File;
import com.gjq.springboot.entity.downDTO;
import com.gjq.springboot.utils.FtpUtil;
import org.apache.commons.net.ftp.FTPFile;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;


import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@RestController
@CrossOrigin//该注解可以解决跨越问题。
@RequestMapping("/file")
public class FileController {


    @PostMapping("addFile")
    public Object addFile(@RequestParam("file") MultipartFile multipartFile, @RequestParam String selectIndex) throws IOException {

        //System.out.println(selectIndex);
        InputStream inputStream = multipartFile.getInputStream();
        String filename = multipartFile.getOriginalFilename();
        //String suffix = filename.substring(filename.lastIndexOf("."));

        //System.out.println("name"+filename);
        //String finalname = UUID.randomUUID()+suffix;

        boolean flag = FtpUtil.uploadFile(filename, inputStream,selectIndex);
        return flag;
    }



//    @GetMapping("/{id}")
//    @ResponseBody
//    public Object downFile(@PathVariable String id){ //"0c1d3933-9ff9-410d-bc3b-b49d88ea9b51.jpg"
//        System.out.println(id);
//        boolean flag = FtpUtil.downloadFile("d:/" ,id,"");
//        return flag;
//    }
    @GetMapping()
    @ResponseBody
    public ResponseEntity<byte[]> downFile(downDTO downDTO){ //"0c1d3933-9ff9-410d-bc3b-b49d88ea9b51.jpg"
//        if(downDTO.getPath()==null) downDTO.setPath("d:/");
        System.out.println("downDTO "+downDTO.getName()+" "+downDTO.getPath()+" "+downDTO.getZpath());
        //boolean flag = FtpUtil.downloadFile(downDTO.getPath() ,downDTO.getName(), downDTO.getZpath());
        byte[] fileContent = FtpUtil.downloadFile(downDTO.getName(),downDTO.getZpath());

        if (fileContent == null) {
            return new ResponseEntity<>(HttpStatus.NOT_FOUND);
        }

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        headers.setContentDispositionFormData("attachment", downDTO.getName());

        return new ResponseEntity<>(fileContent, headers, HttpStatus.OK);
    }


    @GetMapping("showFile")
    @ResponseBody
    public Object showFile(String path){

        FTPFile[] ftpFiles = (FTPFile[])FtpUtil.getFile(path);
        List<File> Files = new ArrayList<>();
        for(FTPFile file: ftpFiles){
            File file2 = new File();
            //System.out.println(file.getRawListing());
            file2.setFilename(file.getName());
            file2.setSize(file.getSize());
            Calendar cal = Calendar.getInstance();
            cal = file.getTimestamp();
            Integer year = cal.get(Calendar.YEAR);
            String str = file.getRawListing();
            String pattern = "\\b\\w{3}\\s+(\\d{1,2})\\s+(\\d{2}):(\\d{2})\\b";
            Pattern r = Pattern.compile(pattern);
            Matcher m = r.matcher(str);
            String creatTime = null;
            if (m.find()) {
                String month_day = m.group(0);
//                String hour = m.group(2);
//                String minute = m.group(3);
                creatTime = year+" 年 "+month_day;
                //System.out.println(month_day + " " + hour + ":" + minute);
            }

            file2.setCreatTime(creatTime);
            if(file.isFile()){
                file2.setType(1);
            }else file2.setType(2);
            Files.add(file2);
        }
        Collections.sort(Files, new Comparator<File>() {
            @Override
            public int compare(File f1, File f2) {
                return f2.getCreatTime().compareTo(f1.getCreatTime());
            }
        });
        return Files;
    }
    @PutMapping("addFolder")
    @ResponseBody
    public boolean addFolder(@RequestBody File file){
        System.out.println(file.getFilename()+" "+file.getPath());
        return FtpUtil.addFolder(file.getFilename(), file.getPath());
    }

    @GetMapping("/openFolder")
    @ResponseBody
    public Object openFolder(downDTO Path){
        FTPFile[] ftpFiles = (FTPFile[])FtpUtil.openFolder(Path.getPath());
        List<File> Files = new ArrayList<>();
        for(FTPFile file: ftpFiles){
            File file2 = new File();
            //System.out.println(file.getRawListing());
            file2.setFilename(file.getName());
            file2.setSize(file.getSize());
            Calendar cal = Calendar.getInstance();
            cal = file.getTimestamp();
            Integer year = cal.get(Calendar.YEAR);
            String str = file.getRawListing();
            String pattern = "\\b\\w{3}\\s+(\\d{1,2})\\s+(\\d{2}):(\\d{2})\\b";
            Pattern r = Pattern.compile(pattern);
            Matcher m = r.matcher(str);
            String creatTime = null;
            if (m.find()) {
                String month_day = m.group(0);
//                String hour = m.group(2);
//                String minute = m.group(3);
                creatTime = year+" 年 "+month_day;
                //System.out.println(month_day + " " + hour + ":" + minute);
            }

            file2.setCreatTime(creatTime);
            if(file.isFile()){
                file2.setType(1);
            }else file2.setType(2);
            Files.add(file2);
        }
        Collections.sort(Files, new Comparator<File>() {
            @Override
            public int compare(File f1, File f2) {
                return f2.getCreatTime().compareTo(f1.getCreatTime());
            }
        });
        return Files;
    }

}
